<template>
    <div class="img-upload">
        <!-- 单图 -->
        <ul class="el-upload-list el-upload-list--picture-card" v-if="!multiple">
            <li class="el-upload-list__item is-success" v-if="imgUrl!=''">
                <img class="el-upload-list__item-thumbnail" :src="imgUrl.includes('data:')?imgUrl:imgUrl" alt="">
                <span class="el-upload-list__item-actions">
                    <span class="el-upload-list__item-preview" @click="handleViewer(0)">
                        <i class="el-icon-zoom-in"></i>
                    </span>
                    <span v-if="!detail" class="el-upload-list__item-delete" @click="handleRemove()">
                        <i class="el-icon-delete"></i>
                    </span>
                </span>
            </li>
            <li v-else-if="detail">
                <div class="no-img">暂无图片</div>
            </li>
        </ul>
        <!-- 多图 -->
        <ul class="el-upload-list el-upload-list--picture-card" v-if="multiple && !showNum">
            <li v-if="imgListData.length==0 && detail">
                <div class="no-img">暂无图片</div>
            </li>
            <li class="el-upload-list__item is-success" v-for="(item,index) in imgListData" v-else :key="index">
                <img class="el-upload-list__item-thumbnail" v-if="props" :src="item[props].includes('data:')?item[props]:item[props]" alt="">
                <img class="el-upload-list__item-thumbnail" v-else :src="item.includes('data:')?item:item" alt="">
                <span class="el-upload-list__item-actions">
                    <span class="el-upload-list__item-preview" @click="handleViewer(index)">
                        <i class="el-icon-zoom-in"></i>
                    </span>
                    <span v-if="!detail" class="el-upload-list__item-delete" @click="handleRemove(index)">
                        <i class="el-icon-delete"></i>
                    </span>
                </span>
            </li>
        </ul>
        <!-- 多图只显示一张，并且显示数量 -->
        <ul class="el-upload-list el-upload-list--picture-card" v-if="multiple && showNum">
            <li v-if="imgListData.length==0 && detail">
                <div class="no-img">暂无图片</div>
            </li>
            <li class="el-upload-list__item is-success" v-else>
                <img class="el-upload-list__item-thumbnail" v-if="props"
                    :src="imgListData[0][props].includes('data:')?imgListData[0][props]:imgListData[0][props]" alt="">
                <img class="el-upload-list__item-thumbnail" v-else :src="imgListData[0].includes('data:')?imgListData[0]:imgListData[0]" alt="">
                <em class="show-num">{{imgListData.length}} 张</em>
                <span class="el-upload-list__item-actions">
                    <span class="el-upload-list__item-preview" @click="handleViewer(0)">
                        <i class="el-icon-zoom-in"></i>
                    </span>
                </span>
            </li>
        </ul>
        <div class="paste-con" id="preview" v-on:paste="handlePaste"
            v-show="!detail && ((!multiple && imgUrl=='') || (multiple && imgListData.length<limit))">
            <div class="file-con">
                <input type="file" @change="uploadImg" accept="image/*" :multiple="multiple" ref="upload">
                <el-button size="small" type="primary">点击上传</el-button>
            </div>
            <span>或粘贴图片到此处</span>
        </div>
        <image-viewer v-if="viewerShow" :on-close="close" :url-list="viewerList" :initialIndex="curIndex" :props="props"></image-viewer>
    </div>
</template>

<script>
import imageViewer from './image-viewer'
import { compressImage } from './CompressImageUtils'
export default {
    props: {
        multiple: {
            type: Boolean,
            delfault: false
        },
        imgUrl: {
            type: String,
            default: '',
        },
        imgFile: '',
        imgList: {
            type: Array,
            default: function () {
                return []
            },
        },
        imgForm: {
            type: Array,
            default: function () {
                return []
            }
        },
        limit: {
            type: Number,
            default: 5
        },
        detail: {
            type: Boolean,
            default: false
        },
        props: String,
        showNum: {
            type: Boolean,
            default: false
        }
    },
    components: { imageViewer },
    data() {
        return {
            curIndex: -1,
            dialogVisible: false,
            dialogImg: '',
            viewerShow: false,
            viewerList: [],
            imgFromData: this.imgForm,
            imgListData: this.imgList
        }
    },
    watch: {
        imgList(val){
            this.imgListData=val;
        },
        imgFromData(val) {
            this.$emit('update:imgForm', val)
        },
        imgListData(val) {
            this.$emit('update:imgList', val);
            this.$parent.validate()
        }
    },
    created(){
        console.log(this.imgForm,"this.imgForm")
    },
    methods: {
        close() {
            this.viewerShow = false;
        },
        handleViewer(index) {
            if (!this.multiple) {
                this.viewerList = [this.imgUrl];
                this.curIndex = index;
            } else {
                this.viewerList = this.imgListData;
                this.curIndex = index;

            }
            this.viewerShow = true;
        },
        handlePreview(file) {
            if (!this.multiple) {
                this.dialogImg = this.imgUrl;
            } else {
                if (this.props) {
                    this.dialogImg = file[this.props];
                } else {
                    this.dialogImg = file;
                }

            }
            this.dialogVisible = true;
        },
        handleRemove(index) {
            if (!this.multiple) {
                this.$emit('update:imgUrl', '');
                this.$emit('update:imgFile', {});
                this.$parent.validate()
            } else {
                if (this.imgListData[index].includes('data:') || (this.props && this.imgListData[index][this.props].includes('data:'))) {
                    this.imgFromData.splice(index, 1);
                }
                this.imgListData.splice(index, 1);
            }
        },
        uploadImg(e) {
            console.log(e,"eeeeee")
            let self = this;
            let files = e.target.files;
            if (!e || !window.FileReader) return;
            this.getUrl(0, files, this.imgListData.length);
        },
        getUrl(i, files, oldLength) {
            let self = this;
            if (i + oldLength >= self.limit) {
                self.$message.error(`最多上传${self.limit}张图片`);
                self.$refs.upload.value = '';
                return
            }
            let reader = new FileReader();
            reader.readAsDataURL(files[i]);
            reader.onload = async function () {
                if (files[i].size / 1024 > 400) {
                    await compressImage(reader.result).then(result => {
                        if (result[1].size < files[i].size) {
                            self.setData(result[0], result[1])
                        } else {
                            self.setData(reader.result, files[i])
                        }
                    })
                } else {
                    self.setData(reader.result, files[i]);
                }
                i++;
                if (i < files.length) {
                    self.getUrl(i, files, oldLength);
                } else {
                    self.$refs.upload.value = '';
                }
            }
        },
        setData(url, dataForm) {
            if (!this.multiple) {
                this.$emit('update:imgUrl', url);
                this.$emit('update:imgFile', dataForm);
                this.$parent.clearValidate()
            } else {
                if (this.imgListData.length < this.limit) {
                    if (this.props) {
                        this.imgListData.push({
                            [this.props]: url
                        })
                    } else {
                        this.imgListData.push(url);
                    }
                    this.imgFromData.push(dataForm);
                }
            }
        },
        handlePaste(e) {
            let self = this;
            const items = (e.clipboardData || window.clipboardData).items;
            let file = null;
            if (!items || items.length === 0) {
                this.$message.error("当前浏览器不支持本地");
                return;
            }
            for (let i = 0; i < items.length; i++) {
                if (items[i].type.includes("image")) {
                    file = items[i].getAsFile();
                }
            }
            if (!file) {
                this.$message.error("粘贴内容非图片");
                return;
            }
            let reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = async function () {
                if (file.size / 1024 > 400) {
                    await compressImage(reader.result).then(result => {
                        if (result[1].size < file.size) {
                            self.setData(result[0], result[1])
                        } else {
                            self.setData(reader.result, file)
                        }
                    })
                } else {
                    self.setData(reader.result, file);
                }
                e.srcElement.value = "";
            }
            this.file = file;
        },
    }
};
</script>
<style lang="scss" scoped>
.show-num {
    position: absolute;
    bottom: 0;
    right: 0;
    background: rgba($color: #000000, $alpha: 0.6);
    color: #fff;
    display: inline-block;
    padding: 0px 10px;
    font-style: normal;
}
.paste-con {
    display: inline-block;
    width: 148px;
    height: 148px;
    border: 1px dashed #d9d9d9;
    text-align: center;
    padding-top: 45px;
    margin-bottom: 8px;
    border-radius: 6px;
    >span {
        margin-top: 10px;
        display: inline-block;
    }
}
.no-img {
    margin-bottom: 8px;
    width: 146px;
    height: 146px;
    text-align: center;
    line-height: 146px;
    border-radius: 6px;
    color: #999;
    border: 1px dashed #d9d9d9;
}
.file-con {
    width: 80px;
    height: 32px;
    margin: 0 auto;
    overflow: hidden;
    position: relative;
    input {
        position: absolute;
        top: 0;
        left: calc(50% - 40px);
        margin-left: -80px;
        height: 32px;
        opacity: 0;
        cursor: pointer;
    }
}
/deep/.el-dialog__header {
    border-bottom: none;
}
.el-upload-list--picture-card .el-upload-list__item-thumbnail {
    object-fit: cover;
}
.img-upload .el-upload-list--picture-card {
    line-height: 0;
    position: relative;
}
</style>